package serializer

import (
	"context"
	"gin_mall_tmp/conf"
	"gin_mall_tmp/dao"
	"gin_mall_tmp/model"
)

type Order struct {
	ID            uint    `json:"id"`
	OrderNum      uint64  `json:"orderNum"`
	CreatedAt     int64   `json:"createdAt"`
	UpdatedAt     int64   `json:"updatedAt"`
	UserId        uint    `json:"userId"`
	ProductId     uint    `json:"productId"`
	BossId        uint    `json:"bossId"`
	Num           uint    `json:"num"`
	AddressName   string  `json:"addressName"`
	AddressPhone  string  `json:"addressPhone"`
	Address       string  `json:"address"`
	Type          uint    `json:"type"`
	ProductName   string  `json:"productName"`
	ImgPath       string  `json:"imgPath"`
	DiscountPrice string  `json:"discountPrice"`
	Money         float64 `json:"money"`
}

func BuildOrder(order *model.Order, product *model.Product, address *model.Address) Order {
	return Order{
		ID:            order.ID,
		OrderNum:      order.OrderNum,
		CreatedAt:     order.CreatedAt.Unix(),
		UpdatedAt:     order.UpdatedAt.Unix(),
		UserId:        order.UserId,
		ProductId:     order.ProductId,
		BossId:        order.BossId,
		Num:           uint(order.Num),
		AddressName:   address.Name,
		AddressPhone:  address.Phone,
		Address:       address.Address,
		Type:          order.Type,
		ProductName:   product.Name,
		ImgPath:       conf.Host + conf.HttpPort + conf.ProductPhotoPath + product.ImgPath,
		DiscountPrice: product.DiscountPrice,
		Money:         order.Money,
	}
}

func BuildOrders(ctx context.Context, items []*model.Order) (orders []Order) {
	productDao := dao.NewProductDao(ctx)
	addressDao := dao.NewAddressDao(ctx)

	for _, item := range items {
		product, err := productDao.GetProductById(item.ProductId)
		if err != nil {
			continue
		}
		address, err := addressDao.GetAddressByAid(item.AddressId)
		if err != nil {
			continue
		}
		order := BuildOrder(item, product, address)
		orders = append(orders, order)
	}
	return orders
}
